package com.yy.main.app.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.random.YYRandomKits;
import com.yy.kit.secure.YYSecureKits;
import com.yy.kit.string.YYStrKits;
import com.yy.main.app.mapper.TUserMapper;
import com.yy.main.app.service.IUserService;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.TUser;
import com.yy.pojo.base.TUserExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 存储用户信息。 前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017-08-22
 */
@Controller
@RequestMapping("/user")
@Api(value = "用户的controller", tags = {"用户的controller"})
public class UserController extends CommonController {
    @Resource(name = "iUserService")
    private IUserService iUserService;
    @Autowired
    private TUserMapper tUserMapper;

    @InitBinder
    @ApiOperation(value = "表单与用户绑定时日期字段的处理")
    public void InitBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    /**
     * <p>
     * 跳转到用户管理页面
     * </p>
     *
     * @param session 应用中的会话
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月14日
     */
    @ApiOperation(value = "跳转到用户管理页面", httpMethod = "GET", notes = "跳转到用户管理页面，用户必须拥有user:manager权限")
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @HasPers(name = "user:manager")
    public ModelAndView userList(HttpSession session) {
        return goToPageByModelAndView("system/user/user_list", null, getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 保存用户信息
     * </p>
     *
     * @param user 用户实体
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月7日
     */
    @RequestMapping(value = "/saveuser", method = RequestMethod.POST)
    @ApiOperation(value = "保存用户信息", httpMethod = "POST", notes = "保存用户信息")
    public @ResponseBody
    Map<String, Object> saveuser(TUser user) {
        Map<String, Object> result = YYMapKits.createHashMap();
        if (YYStrKits.isBlank(user.getId()) || "-1".equals(user.getId())) {// 增加
            user.setId(YYStrKits.getTableId());
            user.setCreate_date(new Date());
            // 判断帐号是否重复
            TUserExample userExample = new TUserExample();
            userExample.createCriteria().andAccountEqualTo(user.getAccount());

            long accountCount = tUserMapper.countByExample(userExample);

            if (accountCount > 0) {
                result.put("success", Boolean.FALSE);
                result.put("msg", "用户帐号重复，请重试!!");
                return result;
            }

            TUserExample uExample = new TUserExample();
            uExample.createCriteria().andEmailEqualTo(user.getEmail());
            long emailCount = tUserMapper.countByExample(uExample);

            if (emailCount > 0) {
                result.put("success", Boolean.FALSE);
                result.put("msg", "用户邮箱重复，请重试!!");
                return result;
            }
            // 密码与帐号相同
            user.setPassword(YYSecureKits.md5(user.getAccount()));
            // 用户编号先生成个10位的随机数
            user.setUser_num(Long.parseLong(YYRandomKits.randomNumbers(10)));
            Integer b = tUserMapper.insert(user);
            if (b > 0) {
                result.put("success", Boolean.TRUE);
                result.put("msg", "增加用户成功!!");
            } else {
                result.put("success", Boolean.FALSE);
                result.put("msg", "增加用户失败，请重试!!");
            }
        } else {// 修改
            // 判断帐号是否重复
            TUserExample example1 = new TUserExample();
            example1.createCriteria()
                    .andAccountEqualTo(user.getAccount())
                    .andIdNotEqualTo(user.getId());

            long accountCount = tUserMapper.countByExample(example1);
            if (accountCount > 0) {
                result.put("success", Boolean.FALSE);
                result.put("msg", "用户帐号重复，请重试!!");
                return result;
            }

            // 判断邮箱是否重复
            TUserExample example2 = new TUserExample();
            example2.createCriteria()
                    .andEmailEqualTo(user.getEmail())
                    .andIdNotEqualTo(user.getId());

            long emailCount = tUserMapper.countByExample(example2);

            if (emailCount > 0) {
                result.put("success", Boolean.FALSE);
                result.put("msg", "用户邮箱重复，请重试!!");
                return result;
            }

            user.setUpdate_date(new Date());
            Integer b = tUserMapper.updateByPrimaryKeySelective(user);
            if (b > 0) {
                result.put("success", Boolean.TRUE);
                result.put("msg", "修改用户成功!!");
            } else {
                result.put("success", Boolean.FALSE);
                result.put("msg", "修改用户失败，请重试!!");
            }
        }
        return result;
    }

    /**
     * <p>
     * 跳转到编辑用户的页面
     * </p>
     *
     * @param id 用户ID
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月6日
     */
    @RequestMapping("/userform/{id}")
    @HasPers(name = "user:add,user:update")
    @ApiOperation(value = "跳转到编辑用户的页面", httpMethod = "GET", notes = "跳转到编辑用户的页面,用户需要拥有user:add,user:update权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "form")})
    public ModelAndView goBugForm(@PathVariable("id") String id, HttpServletRequest request) {
        TUser user = getCurrentUser(request.getSession());
        TUser us = tUserMapper.selectByPrimaryKey(id);// 如果是新增id肯定是-1
        if (null == us) {
            us = new TUser();
            us.setId("-1");
        }
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("user", us);
        return goToPageByModelAndView("system/user/user_form", param, user.getId());
    }

    /**
     * <p>
     * 获得管理端用户的数据表格
     * </p>
     *
     * @param page    当前页
     * @param limit   每页显示多少条数据
     * @param status  用户状态
     * @param name    用户名
     * @param usernum 用户编号
     * @param sex     性别
     * @author 杨阳
     * @since 2017年9月14日
     */
    @RequestMapping(value = "/userTable", method = RequestMethod.GET)
    @ApiOperation(value = "获得管理端用户的数据表格", httpMethod = "GET", notes = "获得管理端用户的数据表格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "用户状态1.正常 2.锁定", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "真实姓名", paramType = "query"),
            @ApiImplicitParam(name = "usernum", value = "用户编号，暂时应该没啥用", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别 1.男 2.女", paramType = "query")
    })
    @ResponseBody
    public Map<String, Object> userTable(Integer page, Integer limit,
                                         String status, String name,
                                         String usernum, String sex) {
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();

        if (null != status && !"".equals(status)) {
            criteria.andStatusEqualTo(Integer.parseInt(status));
        }
        if (null != usernum && !"".equals(usernum)) {
            criteria.andUser_numEqualTo(Long.parseLong(usernum));
        }
        if (null != name && !"".equals(name)) {
            criteria.andNameLike(YYStrKits.like(name));
        }
        if (null != sex && !"".equals(sex)) {
            criteria.andSexEqualTo(Integer.parseInt(sex));
        }
        example.setOrderByClause("create_date desc, update_date desc");
        PageHelper.startPage(page, limit);
        List<TUser> userList = tUserMapper.selectByExample(example);
        return super.pageToMap(new PageInfo(userList));
    }

    /**
     * <p>
     * 删除用户
     * </p>
     *
     * @param id 用户id
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月15日
     */
    @RequestMapping(value = "/deluser/{id}", method = RequestMethod.POST)
    @HasPers(name = "user:delete")
    @ApiOperation(value = "删除用户", httpMethod = "GET", notes = "删除用户,需要拥有user:delete权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    @ResponseBody
    public Map<String, Object> deluser(@PathVariable("id") String id) {
        Map<String, Object> map = YYMapKits.createHashMap();
        Integer b = tUserMapper.deleteByPrimaryKey(id);
        if (b > 0) {
            map.put("success", Boolean.TRUE);
            map.put("msg", "删除成功!");
        } else {
            map.put("success", Boolean.FALSE);
            map.put("msg", "删除失败，请重试!");
        }
        return map;
    }

    /**
     * <p>
     * 查看用户详情
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月15日
     */
    @RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
    @HasPers(name = "user:show")
    @ApiOperation(value = "查看用户详情", httpMethod = "GET", notes = "查看用户详情,需要拥有user:show权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
    })
    public ModelAndView show(@PathVariable("id") String id) {
        TUser user = tUserMapper.selectByPrimaryKey(id);
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("user", user);
        return goToPageByModelAndView("system/user/user_show", param);
    }

}
